package cn.bone.stress.web;

import cn.bone.stress.bean.ErrorRecord;
import cn.bone.stress.dao.ErrorRecordDao;
import cn.bone.stress.service.ApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.concurrent.FailureCallback;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.util.concurrent.SuccessCallback;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import javax.annotation.Resource;
import java.util.Date;


/**
 * Created by superbone on 2017/3/27.
 */
@RestController
public class ApiController {

    @Resource
    private ApiService apiService;
    @Resource
    private ErrorRecordDao errorRecordDao;

    private Logger logger = LoggerFactory.getLogger("web");

    @RequestMapping("/api")
    public DeferredResult<String> api() {

        logger.info("进入api");

        final DeferredResult<String> deferredResult =
                new DeferredResult<>(3500L,"超时了");

        ListenableFuture<String> future = apiService.asyncExecute();
        future.addCallback(new ListenableFutureCallback<String>(){

            @Override
            public void onSuccess(String result) {
                logger.info("onSuccess");
                deferredResult.setResult(result);
            }

            @Override
            public void onFailure(Throwable ex) {
                logger.info("onFailure");
                ErrorRecord record = new ErrorRecord();
                record.setCreateTime(new Date());
                record.setExceptionClass(ex.getClass().getName());
                record.setExceptionMessage(ex.getMessage());
                record.setExceptionPoint(ex.getCause().getMessage());
                record.setExceptionLocalizedMessage(ex.getLocalizedMessage());
                errorRecordDao.save(record);
                deferredResult.setResult("error");
            }
        });

        return deferredResult;
    }

    @RequestMapping("/err")
    public DeferredResult<String> error(){
        final DeferredResult<String> deferredResult =
                new DeferredResult<>(3500L,"超时了");

        ListenableFuture<String> future = apiService.error();
        future.addCallback(new ListenableFutureCallback<String>(){

            @Override
            public void onSuccess(String result) {
                logger.info("onSuccess");
                deferredResult.setResult("onSuccess");
            }
            @Override
            public void onFailure(Throwable ex) {
                logger.info("onFailure");
                deferredResult.setResult("error");
            }
        });
        return deferredResult;
    }

}
